<script setup>
import { ref, reactive, computed } from 'vue'
import { GetMenuPermAPI } from '@/api/system/billconfig'
import dayjs from 'dayjs'
import { GetTreeAPI } from '@/api/system/shopAdministration/modeling'
// 车间选择数据
const treeData = ref([])

// 层级下拉
const treeSelsct = ref([])
const Props = defineProps({
  SelectForm: {
    type: Array,
    default: () => []
  },
  isShow: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['selectSubmit', 'timeChange', 'reset', 'selectChange'])
// 展开缩放
const zhankai = ref(false)

// 表单数据绑定
const Form = reactive({
  bilds: '',
  Time: '',
  startTime: '',
  endTime: '',
  yarnMonths: ''
})
const Time = ref('')
const monthTime = ref('') //年月查询字段
// 下拉选择时
const selectChange = val => {
  if (val.isGo) emit('selectChange', Form[val.model])
}

// 时间范围选择时
const timeChange = val => {
  if (!val) {
    Form.startTime = ''
    Form.endTime = ''
    return
  } else {
    Form.startTime = `${Time.value[0]} 00:00:00`
    Form.endTime = `${Time.value[1]} 23:59:59`
  }

  emit('timeChange', Time)
}

//年月范围改变
const changeMonthrange = val => {
  if (!val) {
    Form.beginMonthTime = ''
    Form.endMonthTime = ''
    return
  } else {
    Form.beginMonthTime = monthTime.value[0]
    Form.endMonthTime = monthTime.value[1]
  }
  emit('changeMonthrange', monthTime)
}

// 默认时间(beginMonthTime ，endMonthTime 年月范围 范围)
const defYarnMonthTime = () => {
  const firstDayOfMonth = dayjs().startOf('month')
  const staTime = firstDayOfMonth.format('YYYY-MM')
  const endTime = dayjs().format('YYYY-MM')
  monthTime.value = [staTime, endTime]
  Form.beginMonthTime = staTime
  Form.endMonthTime = endTime
}

// 单独查询年月
const changeyarnMonths = val => {
  Form.yarnMonths = val
  emit('changeyarnMonths', Form.yarnMonths)
}

// 默认时间(单独年月查询)
const yarnMonthsDefaultTime = () => {
  Form.yarnMonths = dayjs().format('YYYY-MM')
}

// 提交查询
const Submit = () => {
  emit('selectSubmit', Form, 'Submit')
}

/**
 * 如果传来的数据类型有年月范围则执行赋值默认年月范围并查询
 */
const defYarnMonth = () => {
  const isIf = Props.SelectForm.some(item => item.type == '年月范围')
  if (!isIf) return
  defYarnMonthTime()
  Submit()
}
defYarnMonth()

/**
 * 如果传来的数据类型有单独年月则执行赋值默认年月并查询
 */
const yarnMonthsDefault = () => {
  const isIf = Props.SelectForm.some(item => item.type == '单独年月')
  if (!isIf) return
  yarnMonthsDefaultTime()
  Submit()
}
yarnMonthsDefault()

// 重置查询条件
const reset = () => {
  for (let Key in Form) {
    Form[Key] = ''
  }
  Time.value = ''
  monthTime.value = ''
  Form.yarnMonths = ''
  const isIf = Props.SelectForm.some(item => item.type == '年月范围')
  if (isIf) {
    defYarnMonthTime()
  }
  const isIn = Props.SelectForm.some(item => item.type == '单独年月')
  if (isIn) {
    yarnMonthsDefault()
  }
  emit('selectSubmit', Form, 'reset')
}

//
const nodeClick = model => {
  Form[model] = Form.bilds[Form.bilds.length - 1]
}

// 获取层级下拉
const getTreeSelsct = async () => {
  try {
    const res = await GetMenuPermAPI()
    treeSelsct.value = res.data
  } catch {
  } finally {
  }
}
getTreeSelsct()
// 获取树结构
const getTree = async () => {
  try {
    const res = await GetTreeAPI()
    treeData.value = res.theDrop
  } catch {
  } finally {
  }
}
getTree()

watch(
  () => Props.SelectForm,
  val => {
    if (val.length > 4) zhankai.value = true
  },
  {
    deep: true,
    immediate: true
  }
)

const arrList = computed(() => {
  if (Array.isArray(Props.SelectForm) && Props.SelectForm?.length > 0) {
    return Props.SelectForm
  } else {
    console.error(new Error('模糊查询枚举数据错误！'))
    return []
  }
})
defineExpose({ Form })
</script>

<template>
  <div class="boxM" :class="zhankai || Props.isShow ? 'boxM_av' : 'boxM'">
    <div class="Box">
      <el-form :inline="true" label-width="100px">
        <el-form-item :label="item.label || '时间选择'" v-for="(item, index) in arrList" :key="index">
          <!-- 输入 -->
          <el-input
            clearable
            @keyup.enter="Submit"
            v-model.trim="Form[item.model]"
            v-if="item.type === '输入框'"
            :placeholder="`请输入${item.label}`"
          />
          <!-- 层级下拉 -->
          <el-cascader
            v-if="item.type === '层级下拉'"
            :placeholder="`请输入${item.label}`"
            @keyup.enter="Submit"
            v-model="Form.bilds"
            :options="item.opt || treeSelsct"
            :node-key="item?.config?.key || 'menuId'"
            :props="item?.config || { value: 'menuId', label: 'menuName', children: 'children' }"
            @change="nodeClick(item.model)"
          />
          <!-- 树结构下拉 -->
          <el-tree-select
            clearable
            check-strictly
            v-if="item.type === '树结构下拉'"
            @keyup.enter="Submit"
            v-model="Form[item.model]"
            :data="item.opt || treeData"
            :placeholder="`请选择${item.label}`"
            :node-key="item?.config?.key || 'id'"
            :props="item?.config || { value: 'code', label: 'name' }"
            :render-after-expand="false"
          />
          <!-- 下拉 -->
          <el-select
            @keyup.enter="Submit"
            v-model="Form[item.model]"
            clearable
            :placeholder="`请选择${item.label}`"
            v-if="item.type === '下拉单选'"
            @change="selectChange(item)"
          >
            <el-option v-for="(item, index) in item.opt" :key="index" :label="item.label" :value="item.value" />
          </el-select>
          <!-- 时间范围 -->
          <el-date-picker
            style="width: 220px"
            v-if="item.type === '日期范围'"
            v-model="Time"
            type="daterange"
            range-separator="-"
            start-placeholder="开始"
            end-placeholder="结束"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            @change="timeChange"
          />

          <!-- 年月范围选择 -->
          <el-date-picker
            v-if="item.type === '年月范围'"
            v-model="monthTime"
            type="monthrange"
            format="YYYY-MM"
            value-format="YYYY-MM"
            start-placeholder="开始"
            end-placeholder="结束"
            range-separator="-"
            @change="changeMonthrange"
          />

          <!-- 单独年月 -->
          <el-date-picker
            v-if="item.type === '单独年月'"
            v-model="Form.yarnMonths"
            type="month"
            placeholder="请选择年月"
            format="YYYY-MM"
            value-format="YYYY-MM"
            @change="changeyarnMonths"
          />
        </el-form-item>
      </el-form>
      <!-- 按钮 -->
      <div class="Button" v-show="!Props.isShow">
        <el-button type="primary" @click="Submit">查询</el-button>
        <el-button @click="reset">重置</el-button>
        <!-- 展开 -->
        <div style="display: inline; margin-left: 10px" class="zhankai" @click="zhankai = !zhankai">
          <el-tooltip class="box-item" effect="dark" content="展开/缩放" placement="top-start">
            <el-icon :class="zhankai ? 'icons_av' : 'icons'"><ArrowDownBold /></el-icon>
          </el-tooltip>
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.Box {
  padding: 0 20px;
  // margin: 20px 0;
  // margin-top: 20px;
  display: flex;
  // justify-content: center;
}
.Button {
  min-width: 160px;
}

.boxM {
  transition: all 0.5s;
  height: 50px;
  overflow: hidden;
}

.boxM_av {
  transition: all 0.5s;
  height: 100%;
  overflow: hidden;
}
.icons_av {
  transition: all 0.5s;
  transform: rotate(180deg);
}
.icons {
  transition: all 0.5s;
  transform: rotate(0deg);
}

.zhankai {
  cursor: pointer;
}
</style>
